<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="床位编号" prop="bedId">
        <el-input
          v-model="queryParams.bedId"
          placeholder="请输入床位编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="床位类型" prop="btypeId">
        <el-input
          v-model="queryParams.btypeId"
          placeholder="请输入床位类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者信息" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          placeholder="请输入患者信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生信息" prop="doctorId">
        <el-input
          v-model="queryParams.doctorId"
          placeholder="请输入医生信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="护士信息" prop="nurseId">
        <el-input
          v-model="queryParams.nurseId"
          placeholder="请输入护士信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手术预约" prop="surgeryAppointment">
        <el-input
          v-model="queryParams.surgeryAppointment"
          placeholder="请输入手术预约"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否入住" prop="checkedIn">
        <el-input
          v-model="queryParams.checkedIn"
          placeholder="请输入是否入住"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:reserve:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:reserve:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:reserve:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:reserve:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reserveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="预约id" align="center" prop="reserveId" />
      <el-table-column label="床位编号" align="center" prop="bedId" />
      <el-table-column label="床位类型" align="center" prop="btype.btypeName" />
      <el-table-column label="患者信息" align="center" prop="patient.patientName" />
      <el-table-column label="医生信息" align="center" prop="doctorId" :formatter="formatDoctor" />
      <el-table-column label="护士信息" align="center" prop="nurseId" :formatter="formatNurse" />
      <el-table-column label="手术预约" align="center" prop="surgeryAppointment"  >
        <template slot-scope="scope">
          <span v-if="scope.row.surgeryAppointment">{{ scope.row.surgeryAppointment }}</span>
          <span v-else>暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" >
        <template slot-scope="scope">
          <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
          <span v-else>暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="是否入住" align="center" prop="checkedIn" :formatter="formatCheckedIn" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:reserve:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleCheckIn(scope.row)"
            v-hasPermi="['system:reserve:checkInBed']"
          >入住
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:reserve:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="床位类型" prop="bedId">
          <el-select v-model="form.bedId"  @change="handleBedChange"  filterable placeholder="请选择床位类型">
            <el-option
              v-for="item in bedOptions"
              :key="item.bedId"
              :label="item.btype.btypeName"
              :value="item.bedId"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="床位类型组" prop="btypeId">-->
<!--          <el-input v-model="form.btypeId" placeholder="请输入床位类型组" />-->
<!--        </el-form-item>-->
        <el-form-item label="患者信息" prop="patientId">
          <el-select v-model="form.patientId" filterable placeholder="请输入患者信息">
            <el-option
              v-for="item in patientOptions"
              :key="item.patientId"
              :label="item.patientName"
              :value="item.patientId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生信息" prop="doctorId">
          <el-select v-model="form.doctorId" filterable placeholder="请选择医生">
            <el-option
              v-for="item in doctorOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="护士信息" prop="nurseId">
          <el-select v-model="form.nurseId" :label="form.doctorName" filterable placeholder="请选择护士">
            <el-option
              v-for="item in nurseOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            ></el-option>
          </el-select>        </el-form-item>
        <el-form-item label="手术预约" prop="surgeryAppointment">
          <el-input v-model="form.surgeryAppointment" placeholder="请输入手术预约" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listReserve, getReserve, delReserve, addReserve, updateReserve, checkInBed } from "@/api/system/reserve";
  import { listPatient } from '@/api/system/patient'
  import { listBed, getBed, delBed, addBed, updateBed,dischargeBed } from '@/api/system/bed'
  import {
    listUser,
    getUser,
    delUser,
    addUser,
    updateUser,
    resetUserPwd,
    changeUserStatus,
    deptTreeSelect
  } from '@/api/system/user'

  export default {
    name: "Reserve",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 预约信息表格数据
        reserveList: [],
        //医生选项
        doctorOptions: [],
        //患者选项
        patientOptions: [],
        //护士选项
        nurseOptions: [],
        //床位信息
        bedOptions:[],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          bedId: null,
          btypeId: null,
          patientId: null,
          doctorId: null,
          nurseId: null,
          surgeryAppointment: null,
          checkedIn: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          bedId: [
            { required: true, message: "床位编号不能为空", trigger: "blur" }
          ],
          btypeId: [
            { required: true, message: "床位类型不能为空", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();
      this.getIdType();
      this.getPatient();
      this.getBedList();
    },
    methods: {
      formatDoctor(row) {
        // 在 doctorOptions 数组中查找匹配的 doctorId，并返回对应的 doctorName
        const doctor = this.doctorOptions.find(doc => doc.userId === row.doctorId);
        return doctor ? doctor.userName : '';
      },
      formatNurse(row) {
        // 在 nurseOptions 数组中查找匹配的 nurseId，并返回对应的 nurseName
        const nurse = this.nurseOptions.find(nur => nur.userId === row.nurseId);
        return nurse ? nurse.userName : '';
      },
      handleBedChange() {
        // 在床位编号变化时触发，根据选择的床位编号设置对应的 btypeId
        const selectedBed = this.bedOptions.find(item => item.bedId === this.form.bedId);
        if (selectedBed) {
          this.form.btypeId = selectedBed.btype.btypeId;
        } else {
          this.form.btypeId = ''; // 如果找不到对应的床位，清空 btypeId
        }
      },
      //修改显示
      formatCheckedIn(row, column) {
        const status = row[column.property]
        switch (status) {
          case 0:
            return '未入住'
          case 1:
            return '已入住'
          case 2:
            return '已出院'
          default:
            return ''
        }
      },
      // 获取医生及护士名单
      getIdType() {
        listUser().then(response => {
          this.doctorOptions = response.rows.filter(user => user.identityType === 'D')
          this.nurseOptions = response.rows.filter(user => user.identityType === 'N')
          console.log("---doctorOptions---",this.doctorOptions)
        })
      },
      // 获取患者名单
      getPatient() {
        listPatient().then(response => {
          console.log("---listPatient---",response)
          this.patientOptions = response.rows
        })
      },
      // 获取床位名单
      getBedList() {
        listBed().then(response => {
          console.log("---listBed---",response)
          this.bedOptions = response.rows.filter(bed=>bed.status!==2)
        })
      },
      /** 查询预约信息列表 */
      getList() {
        this.loading = true;
        listReserve(this.queryParams).then(response => {
          this.reserveList = response.rows;
          console.log("---reserveList---", response.rows)
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          reserveId: null,
          bedId: null,
          btypeId: null,
          patientId: null,
          doctorId: null,
          nurseId: null,
          surgeryAppointment: null,
          remark: null,
          checkedIn: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.reserveId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加预约信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const reserveId = row.reserveId || this.ids
        getReserve(reserveId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改预约信息";
        });
      },
      /** 预约入住按钮操作 */
      handleCheckIn(row) {
        const bedId = row.bedId || this.ids
        console.log("---row---",row)
        this.$modal.confirm('是否确认入住床位信息编号为"' + bedId + '"的病人项？').then(function() {
          return checkInBed(row)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess('入住成功')
        }).catch(() => {
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          this.form.bedId = parseInt(this.form.bedId, 10); // 10 表示十进制
          console.log('---submit form---', this.form)
          if (valid) {
            if (this.form.reserveId != null) {
              updateReserve(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addReserve(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const reserveIds = row.reserveId || this.ids;
        this.$modal.confirm('是否确认删除预约信息编号为"' + reserveIds + '"的数据项？').then(function() {
          return delReserve(reserveIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/reserve/export', {
          ...this.queryParams
        }, `reserve_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
